<template>
	<view class="wrap">
		<view v-for="(item,index) in list" :key="index">
			<view class="newsL" v-if="item.type==1">
				<image :src="item.img" style="margin-right: 12upx;" class="phto"></image>
				<view class="newsLContent"><p class='txtContent'>{{item.text}}</p></view>
			</view>
			<view class="newsR" v-if="item.type==2">
				<view class="newsRContent"><p class='txtContent'>{{item.text}}</p></view>
				<image class="phto" style="margin-left: 12upx;" :src="useritem.headImage"></image>
			</view>
		</view>
		<view class="chatInput">
			<input class="uni-input" v-model="chatContent" focus placeholder="请输入您要咨询的问题" />
			<view class="chatInputBtn" @click="clickRequest">发送</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				socketTask: null,
				// 确保websocket是打开状态
				is_open_socket: false,
				userInfo: {},
				useritem: {},
				chatContent: '', //消息内容
				list: [{
					type: 1,
					text: '您好，我是华润客服，请问有什 么可以帮您',
					img: '../../../static/images/img/1661928103011.png'
				}],
			}
		},
		onLoad() {
			// 进入这个页面的时候创建websocket连接【整个页面随时使用】
			this.userInfo = uni.getStorageSync('storage_key')
			this.useritem = uni.getStorageSync('storage_userInfo')
			this.connectSocketInit(this.userInfo.buyerUserId);
		},
		// 关闭websocket【必须在实例销毁之前关闭,否则会是underfined错误】
		beforeDestroy() {
			this.closeSocket();
		},
		methods: {
			getNum() {
				var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
					'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
					'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
					'x', 'y', 'z'
				];
				var nums = "";
				for (var i = 0; i < 32; i++) {
					var id = parseInt(Math.random() * 61);
					nums += chars[id];
				}
				return nums;
			},
			connectSocketInit(id) {
				const that = this
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					url: "wss://hr.aimaila.com/ws/" + id, //假地址
					success(data) {
						console.log("websocket连接成功");
					},
				});
				// 消息的发送和接收必须在正常连接打开中,才能发送或接收【否则会失败】
				this.socketTask.onOpen((res) => {
					console.log("WebSocket连接正常打开中...！");
					this.is_open_socket = true;
					// 注：只有连接正常打开中 ，才能正常成功发送消息
					this.socketTask.send({
						data: "uni-app发送一条消息",
						async success() {
							console.log("消息发送成功");
						},
					});
					// 注：只有连接正常打开中 ，才能正常收到消息
					this.socketTask.onMessage((res) => {
						var obj = JSON.parse(res.data)
						console.log(obj);
						if (obj.content) {
							that.list.push({
								type: 1,
								text: obj.content,
								img: obj.fromUser.avatar
							})
							setTimeout(() => {
								uni.pageScrollTo({
									scrollTop: 99999,
									duration: 0
								})
							}, 200)
						}

					});
				})
				// 这里仅是事件监听【如果socket关闭了会执行】
				this.socketTask.onClose(() => {
					console.log("已经被关闭了")
				})
			},
			// 关闭websocket【离开这个页面的时候执行关闭】
			closeSocket() {
				this.socketTask.close({
					success(res) {
						this.is_open_socket = false;
						console.log("关闭成功", res)
					},
					fail(err) {
						console.log("关闭失败", err)
					}
				})
			},
			clickRequest() {
				const _ = this
				if (this.clickRequest) {
					if (this.is_open_socket) {
						let data = {
							"id": _.getNum(),
							"type": "text",
							"status": "succeed",
							"sendTime": Date.now(),
							"toContactId": _.userInfo.buyerUserId,
							"fromUser": {
								"id": _.userInfo.buyerUserId,
								"displayName": _.useritem.name,
								"avatar": _.useritem.headImage
							},
							"content": _.chatContent
						}
						// websocket的服务器的原理是:发送一次消息,同时返回一组数据【否则服务器会进去死循环崩溃】
						this.socketTask.send({
							data: JSON.stringify(data),
							async success() {
								_.list.push({
									type: 2,
									text: _.chatContent
								})
								_.chatContent = '';
								setTimeout(() => {
									uni.pageScrollTo({
										scrollTop: 99999,
										duration: 0
									})
								}, 200)
								console.log("消息发送成功");
							},
						});
					}
				}
			},
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F6F6F6;
	}

	.wrap {
		width: 702upx;
		margin: 0 auto;
		padding-top: 24upx;
		padding-bottom: 200upx;

		.newsL {
			display: flex;
			align-items: center;
			margin-bottom: 24upx;
		}

		.phto {
			width: 80upx;
			height: 80upx;
			border-radius: 40upx;
		}

		.newsLContent {
			max-width: 460upx;
			padding: 12upx 44upx 12upx 24upx;
			color: #333333;
			background-color: #fff;
			border-radius: 0px 40upx 40upx 40upx;
			font-size: 28upx;
			display: flex;
			align-items: center;
			/* #ifdef APP-PLUS */
			.txtContent{
				line-height: 60upx;
			}
			/* #endif */
			
		}

		.newsRContent {
			max-width: 460upx;
			padding: 12upx 44upx 12upx 24upx;
			color: #fff;
			background-color: #EFB257;
			border-radius: 40rpx 0rpx 40rpx 40rpx;
			font-size: 28upx;
			/* #ifdef APP-PLUS */
			.txtContent{
				line-height: 60upx;
			}
			/* #endif */
		}

		.newsR {
			display: flex;
			align-items: center;
			justify-content: flex-end;
			margin-bottom: 24upx;
		}

		.chatInput {
			width: 750upx;
			display: flex;
			position: fixed;
			bottom: 0;
			left: 0;
			height: 150upx;
			background-color: #fff;
			padding: 24upx;
			box-sizing: border-box;

			input {
				width: 575upx;
				height: 80upx;
				border: 1px solid #999;
				border-radius: 8upx;
				padding-left: 24upx;
				box-sizing: border-box;

			}

			.chatInputBtn {
				width: 130upx;
				height: 80upx;
				background-color: #EFB257;
				color: #fff;
				border-radius: 8upx;
				text-align: center;
				line-height: 80upx;
				margin-left: 16upx;
			}
		}
	}
</style>
